<!-- 请使用v-model接收返回的参数-->
<!-- 如需要返回label 请使用nameAndValue=true 并重写@on-change事件-->
<!-- companyId 查询该id的子组织机构,默认值为当前用户的companyId -->
<!-- backLabel 回显用到 -->
<template>
  <Select ref="select" clearable filterable v-model="orgId" placeholder="请选择企业"
          :remote-method="remoteMethodSelectOrg" @on-change="selectChange" :label-in-value="nameAndValue"
          :loading="orgLoading" @input="(e) => {this.$emit('childValueChange',e?e:null)}">
    <Option v-for="(option, index) in orgLists" :value="option.orgId" :key="index">{{ option.orgName }}</Option>
  </Select>
</template>

<script>
import {Api} from "@/api";
import {sessionStorage} from "@/common/cacheUtils";

export default {
  name: "select-org",
  model: {  // 定义model
    prop: 'value',
    event: 'childValueChange'
  },
  props: {
    value: {
      type: String
    },
    nameAndValue: {
      type: Boolean,
      default: false,
    },
    companyId: {
      type: String,
      default: sessionStorage('userId').getObject('userId').companyId,
    },
    backLabel: {
      type: String,
      default: null,
    }
  },
  data() {
    return {
      orgLoading: false,
      orgLists: [],
      orgId: "",
    }
  },
  watch: {
    value: {
      handler(val) {

        this.orgId = val;
      }
    }
  },
  mounted() {
    if (this.backLabel) {
      this.$refs["select"].setQuery(this.backLabel)
    }
    // this.orgId = this.value
  },
  methods: {
    selectChange(data) {
      // this.$emit('childValueChange', this.orgId)
      this.$emit("on-change", data);
    },
    remoteMethodSelectOrg(query) {
      clearTimeout(this.remoteMethodSelectOrg.timer)
      if (query !== '') {
        this.orgLoading = true;
        let data = {
          companyId: this.companyId,
          orgName: query,
          fromPage: 1,
          pageSize: 1000,
        }
        let _this = this;
        this.remoteMethodSelectOrg.timer = setTimeout(() => {
          _this.loading1 = false;
          _this.$http.get(Api.queryOrgList, {params: data}).then(res => {
            _this.orgLists = res.data.data;
            _this.orgLoading = false;
          }).catch(e => {
            _this.orgLoading = false;
            _this.$Message.error('请求失败');
          })
        }, 800);


      } else {
        this.orgLoading = false;
      }
    },
  }
}
</script>

<style scoped>

</style>
